/**
 * 分页查询
 *
 * Created by wbx on 2022/05/01
 * 
 * 参数说明: 
 *      Connection      文本,       连接名称
 *      Text            文本,       SQL语句, 支持?作为参数
 *      Params          对象数组,   SQL绑定参数值, 数组格式
 *      PageSize        整数        每页行数. 指定为0时不分页
 *      PageNo          整数        页码. 默认为1
 */
(function ({ UID, Connection, Text, Params = [], PageSize = 0, PageNo = 1 }) {
    // 验证用户
    if (!UID) throw Error("未授权的访问");

    let Rows = [], Total = 0;

    const query = (conn) => {
        // PageSize为正数时分页
        if (PageSize > 0) {
            let count_sql = "SELECT COUNT(*) TOTAL FROM (" + Text + ") A";
            Total = A.db.execute(conn, count_sql, Params).rows[0].TOTAL;

            const page_sql = conn.provider.paginate(Text, PageSize, PageNo);
            Rows = A.db.execute(conn, page_sql, Params).rows;
        } else {
            Rows = A.db.execute(conn, Text, Params).rows;
            Total = Rows.length;
        }
    };

    if (A.db.trans[Connection]) {
        const conn = A.db.trans[Connection];
        query(conn);
    } else {
        A.db.connect(Connection, query);
    }

    return { Total, Rows, PageNo, PageSize };
});